<?php
/**
 * Created by PhpStorm.
 * User: majiameng <666@majiameng.com>
 * Date: 2017-09-12
 * Time: 17:07
 */

namespace phpcode;

require_once('barcode/class/BCGColor.php');
require_once('barcode/class/BCGDrawing.php');
require_once('barcode/class/BCGcode128.barcode.php');
require_once('qrcode/core/qrlib.php');

class QrCode
{

    /**
     * @param $data '二维码名称信息'
     * @param $parameter '二维码数据信息'
     * @param bool $filePath 'eg. /home/www/uploads/' 默认直接输出文件流到浏览器
     * @param string $size 'eg.1到10 大小'
     * @param string $level '容错率，eg. L|M|Q|H'
     * @return string
     * @throws BadRequestHttpException
     * 获取二维码图片
     */
    public static function getQrCode($data, $parameter, $filePath = false, $size = '10', $level = 'L',$url)
    {
        $cache = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'qrcode/core/cache' . DIRECTORY_SEPARATOR;
        if (!is_dir($cache)) {
            mkdir($cache, 0777, true);
        }
        $errorCorrectionLevel = 'L';
        if (isset($level) && in_array($level, array('L', 'M', 'Q', 'H')))
            $errorCorrectionLevel = $level;
        $matrixPointSize = 4;
        if (isset($size))
            $matrixPointSize = min(max((int)$size, 1), 10);
        if ($filePath) {
            //ofcourse we need rights to create temp dir
            if (!is_dir($filePath)) {
                mkdir($filePath, 0755, true);
            }
            if (isset($data)) {
                //it's very important!
                if (trim($data) == '') throw new BadRequestHttpException('data 不能为空！');
                // user data
                $filename = $filePath . $data . '.png';
                //\QRcode::png($parameter, $filename, $errorCorrectionLevel, $matrixPointSize, 2);
                \QRcode::png($url, $filename, $errorCorrectionLevel, $matrixPointSize, 2);
                return $filename;
            }
        } else {
            if (isset($data)) {
                //it's very important!
                if (trim($data) == '') throw new BadRequestHttpException('data 不能为空！');
                ob_clean();//清空（擦掉）输出缓冲区
                //\QRcode::png($parameter, false, $errorCorrectionLevel, $matrixPointSize, 2);
                \QRcode::png($url, false, $errorCorrectionLevel, $matrixPointSize, 2);
                exit();
                // \QRcode::png($data, false, $errorCorrectionLevel, $matrixPointSize, 2);
            }
        }

    }
}